#!/usr/bin/env python
# encoding: utf-8

def getTestingEnvironment(*jsonFileNames):
	import json
	env = {"prefs":{},"static":{},"context":{},"constants":{},"meta":{},"private":{}}
	for jsonFileName in jsonFileNames:
		contents = json.loads(open(jsonFileName).read())
		for (k,d) in contents.get("prefs",{}).iteritems():
			env["prefs"][k] = d["value"]
		for (k,v) in contents.get("static",{}).iteritems():
			env["static"][k] = v
	return env

def getArchivePath(env,name):
	import errno
	import time
	import os
	directoryPath = os.path.join(env["prefs"]["archiveDirectory"],time.strftime("%Y-%m-%d",time.localtime()))
	try:
		os.makedirs(directoryPath)
	except OSError, e:
		if e.errno != errno.EEXIST:
			raise
	timestamp = time.strftime(env["static"]["cw_archiveTimeFormat"].encode("utf8"),time.localtime()).decode("utf8")
	i = 0
	while os.path.exists(os.path.join(directoryPath,name % (timestamp," - %s" % i if i else ""))):
		i += 1
	return os.path.join(directoryPath,name % (timestamp," - %s" % i if i else ""))

def setTemporaryPrefs(env,temporaryPrefs):
	env["private"]["%s_backupPrefs" % env["meta"]["name"]] = dict((k,env["prefs"][k]) for k in temporaryPrefs)
	env["prefs"].update(temporaryPrefs)

def restoreBackupPrefs(env):
	env["prefs"].update(env["private"]["%s_backupPrefs" % env["meta"]["name"]])
	del env["private"]["%s_backupPrefs" % env["meta"]["name"]]
